﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IPC.Communication.ModBus
{
    public class ModbusAscii : ModbusRtu
    {
        public ModbusAscii()
        {
            LogMsgFormatBinary = false;
        }

        public ModbusAscii(byte station = 1)
            : base(station)
        {
            LogMsgFormatBinary = false;
        }

        protected override byte[] PackCommandWithHeader(byte[] command)
        {
            return ModbusInfo.TransModbusCoreToAsciiPackCommand(command);
        }

        protected override OperateResult<byte[]> UnpackResponseContent(byte[] send, byte[] response)
        {
            OperateResult<byte[]> operateResult = ModbusInfo.TransAsciiPackCommandToCore(response);
            if (!operateResult.IsSuccess)
            {
                return operateResult;
            }
            if (send[1] + 128 == operateResult.Content[1])
            {
                return new OperateResult<byte[]>(operateResult.Content[2], ModbusInfo.GetDescriptionByErrorCode(operateResult.Content[2]));
            }
            return ModbusInfo.ExtractActualData(operateResult.Content);
        }

        public override string ToString()
        {
            return String.Format("ModbusAscii[{0}:{1}]", base.PortName, base.BaudRate);
        }
    }
}
